package services

import (
	"errors"
	"userCRUD/DAO/mysql"
	"userCRUD/model"
	"userCRUD/utils"
)

type userService struct {
}

var (
	ErrorUserExist = errors.New("用户已存在")
	User           = new(userService)
)

func (userService) Login(p *model.UserDTOLogin) (*model.UserVO, error) {
	// 1、从数据库中校验用户名和密码是否正确
	user, err := mysql.User.Login(p.Account, p.Password)
	if err != nil {
		return nil, err
	}

	// 2、登录成功，把 Token 存入 Redis 中
	token := utils.JwtGenerate(int(user.UserId))

	// 3、返回用户数据给 controller
	return &model.UserVO{
		UserId:      user.UserId,
		Account:     user.Account,
		Token:       &token,
		Description: nil,
		UserRole:    user.UserRole,
	}, nil
}

func (userService) GetUserList(params *model.ListParams) ([]*model.User, error) {
	return mysql.User.QueryUserList(params)
}

func (userService) GetUserVOByUserId(userId int64) (*model.UserVO, error) {
	return mysql.User.QueryUserVOByUserId(userId)
}

func (userService) GetUserByUserId(userId int64) (*model.User, error) {
	return mysql.User.QueryUserByUserId(userId)
}

func (userService) AddUser(u *model.UserDTOAdd) (err error) {
	/*if mysql.User.CheckAccountExist(u.Account) {
		return ErrorUserExist
	}
	userID := utils.GenSnowflakeID()*/
	user := &model.User{
		Account:  u.Account,
		Password: u.Password,
	}
	err = mysql.User.Insert(user)
	return
}

func (userService) UpdateUserByAdmin(u *model.UserDTOUpdateByAdmin) error {
	return mysql.User.UpdateUserByAdmin(u)
}
